from functools import wraps
from flask import request

from app.utils.exceptions import MissingParamError


def require_params(*required_fields, include_files=False):
    """验证必填参数装饰器"""

    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            data = {}

            if request.is_json:
                data.update(request.get_json(silent=True) or {})

            data.update(request.form)

            # 如果需要包含文件字段
            if include_files:
                for key in request.files:
                    if request.files[key].filename:  # 只有有文件时才添加
                        data[key] = request.files[key]

            args_data = {}
            for key in request.args.keys():
                print(key)
                if key.endswith('[]'):
                    # 获取完整列表值
                    args_data[key.rstrip('[]')] = request.args.getlist(key)
                else:
                    # 单值处理
                    args_data[key] = request.args.get(key)
                data.update(args_data)

            data.update(kwargs)

            missing = []
            for field in required_fields:
                value = data.get(field)
                print(value)

                # 检查存在性 + 空值（支持多种空值类型）
                is_empty = (
                        value is None or
                        (isinstance(value, str) and value.strip() == '') or
                        (isinstance(value, list) and len(value) == 0) or
                        (isinstance(value, dict) and len(value) == 0)
                )

                if field not in data or is_empty:
                    missing.append(field)

            if missing:
                raise MissingParamError(', '.join(missing))

            # 附加已验证参数到request对象
            request.validated_params = {
                field: data[field] for field in required_fields
            }

            return func(*args, **kwargs)

        return wrapper

    return decorator
